<?php
/**
 * Created by PhpStorm.
 * User: kb130
 * Date: 2018/5/24
 * Time: 11:28
 */

namespace App\Http\Middleware;

use Closure;

/**
 * 用户操作收集中间件
 *
 * Class OperationLogMiddleware
 * @package App\Http\Middleware
 */
class OperationLogMiddleware
{
    public function handle($request, Closure $next, $guard = null)
    {
        return $next($request);
    }

    /**
     * 响应后执行的操作 (添加，修改，删除)
     *
     * @param $request
     * @param $response
     */
    public function terminate($request, $response)
    {
        $user = $request->user();

        if ($response->isOk() && !$request->isMethod('get') && $user && method_exists($user, 'operationLogs')) {
            $route = $request->route();
            $data = [
                'user_id'       => $user->id, // 用户id
                'name'          => $user->name, // 用户名
                'user_model'    => get_class($user), // 用户所属模型
                'exec'          => class_basename($route->getActionName()), // 执行的操作
                'params'        => json_encode(array_merge($request->input(), $route->parameters())), // 传递的参数
                'response_data' => $this->getResponseContent($response) ?? '',
            ];

            // 关联写入operation_logs表
            $user->operationLogs()->create($data);
        }
    }

    protected function getResponseContent($response)
    {
        $data = $response->getContent();

        if (empty($data)) {
            $data = [];
        }

        if (is_array($data)) {
            $data = json_encode($data);
        }

        return $data;
    }
}